import path from 'path'
import helmet from 'koa-helmet'
import cors from 'koa-cors'
import resResult from './resResult'
import comFunc from './comFunc'
import conf from '../config'
const koaJwt = require('koa-jwt')
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const secret = conf.auth.admin_secret
console.log('secret', secret)
export default app => {
  // error handler
  onerror(app)
  app.use(cors({
    origin: function (ctx) {
    //   if (ctx.url === '/test') {
    //     return '*' // 允许来自所有域名请求
    //   }
    //   return 'http://localhost:8080' // 这样就能只允许 http://localhost:8080 这个域名的请求了
      return '*'
    },
    maxAge: 1000,
    credentials: true,
    methods: ['GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept']
  }))
  app.use(resResult())
  app.use(koaJwt({secret}).unless({path: conf.auth.whiteList}))
  // 数据返回的封装
  app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
  }))
  app.use(json())
  app.use(logger())

  // 方法封装
  app.use(comFunc())

  app.use(require('koa-static')(path.resolve(__dirname, '../public')))

  app.use(views(path.resolve(__dirname, '../views'), {
    extension: 'pug'
  }))

  // logger
  app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  })
  app.use(helmet())
}
